// pages/orderConfirm/orderConfirm.js
const app = getApp();
import {
  showToast,
  getUrlParam,
  getWeekByDate,
  getWeekNumByDate,
  getWeekByNum,
  sortToBig,
  trim,
  trim2,
} from '../../utils/util';
import {
  postRequest,
  getRequest,
  postParamsRequest
} from '../../api/request';
import moment from '../../utils/moment';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    myEqCord1: app.globalData.myEqCord1,
    myEqCord2: app.globalData.myEqCord2,
    myEqCord3: app.globalData.myEqCord3,
    myEqCord4: app.globalData.myEqCord4,
    myEqCord5: app.globalData.myEqCord5,
    themeColor: app.globalData.themeColor,
    subColor: app.globalData.subColor,
    btnColor: app.globalData.btnColor,
    baseImg: app.globalData.myTestImg,
    orderId: app.globalData.orderId,
    paymentPriority: wx.getStorageSync('paymentPriority') || 0, //0先付后吃  1先吃后付

    orderMode: 2, //订单方式，1是外卖，2是堂食
    orderType: 2, //订单类型：1-外卖，2-堂食，3-服务员点餐,4-自取，5先吃后付
    isGoodsOpen: false,
    deskName: wx.getStorageSync('deskName'), //桌号
    deskId: "", //桌号id
    checkReceiptTime: "", //预约时间
    checkReceiptWeekList: [], //可预约周
    checkReceiptWeekIndex: 0, //选择的周
    checkReceiptTimeList: [], //可预约时间
    checkReceiptTimeIndex: 0, //选择的时间
    todayString: "", //今天(周四)
    goodsList: [],
    remark: "", //备注
    openRemark: "", //弹窗显示备注
    deliveryInfo: null, //配送信息
    selfTakeMobile: '', //自取联系人电话

    shopInfo: {}, //门店信息
    shopInfo2: {}, //店铺信息
    shopList: [], //门店列表
    userInfo: {}, //用户信息
    isOpenRetention: 0, //是否开启留资信息
    tmplIds: [], //模板
    rechargeDiscountRule: [], //会员充值
    couponList: [], //优惠券
    useCouponList: [], //可用优惠券
    equityCardList: [], //权益卡
    useEquityCardList: [], //可用权益卡
    memberCouponId: [], //选中优惠券id
    memberEquityCardId: '', //选中权益卡
    addressList: [], //收货地址列表
    orderAddress: "", //收货地址
    orderAddress2: "", //选中未确认时

    boxAmt: 0, //餐盒费
    coverChargeAmt: 0, //茶位费
    deliveryAmt: 0, //配送费
    discountAmt: 0, //优惠金额
    equityCardDiscountAmt: 0, //权益卡优惠金额
    payAmt: 0, //实付金额
    serviceChargeAmt: 0, //服务费
    totalAmt: 0, //商品合计
    vipDiscountAmt: 0, //会员折扣
    deliveryOrderId: 0, //配送订单ID
    shopAndMykm: 0, //店铺和我的直线距离

    payType: 1, //支付方式
    payDiscountType: 0, //仅限储值支付享受会员

    isPay: false, //是否支付成功了
    isPlaceOrder: 0, //是否可以预约下单

    showShopList: false,
    showCouponList: false, //优惠券弹窗
    showEquityCardList: false, //权益卡弹窗
    showReceiptTime: false,
    showAddressList: false,
    showRemark: false,
    submitLock: false, //提交锁
    submitClose: true, //是否不允许提交订单
    technicalSupportIcon: '',

    alreadyAdd: 0, //是否已经点过加菜
    useMemberVipDiscount: 1, //是否选择会员折扣
    showVipCoupon: false, //折扣选择弹窗
    useVip: true,

  },
  //扫桌码
  scanTable() {
    // wx.clearStorageSync("deskName")
    // wx.clearStorageSync('deskCode')
    // wx.clearStorageSync('deskId')
    let self = this;
    let tableNum = '';
    let tableId = '';
    wx.scanCode({
      success: (res) => {

        try {
          tableNum = getUrlParam('deskCode', res.path);
          tableId = getUrlParam('deskId', res.path);

          self.setData({
            deskName: tableNum,
            deskId: tableId,
          });
          app.globalData.deskCode = tableNum;
          app.globalData.deskId = tableId;

          wx.setStorageSync('deskName', tableNum)
          wx.setStorageSync('deskCode', tableNum)
          wx.setStorageSync('deskId', tableId)
          this.getQueryDesk()
          wx.showToast({
            title: ' 扫描桌号成功',
            icon: 'success',
            duration: 500
          })
        } catch (e) {
          showToast('二维码不正确');
        };
      }
    })
  },

  //当订单类型改变时
  onOrderTypeChange(e) {

    //判断店铺销售方式
    if (app.shopInfo.salesType.indexOf(e.currentTarget.dataset.type) == -1) {
      let showTitle = "";
      if (e.currentTarget.dataset.type == 1) {
        showTitle = "外卖";
      } else if (e.currentTarget.dataset.type == 2) {
        showTitle = "堂食";
      } else if (e.currentTarget.dataset.type == 4) {
        showTitle = "自取";
      } else if (e.currentTarget.dataset.type == 5) {
        showTitle = "自取";
      }
      wx.showModal({
        title: '提示',
        content: '店铺暂不支持' + showTitle,
        showCancel: false,
        success(res) {
          if (res.confirm) {} else if (res.cancel) {}
        }
      })
      return;
    }
    this.setData({
      orderType: e.currentTarget.dataset.type,
      checkReceiptTimeIndex: 0,
      checkReceiptWeekIndex: 0,
    });
    //重新计算订单
    this.getPreOrder(true, true);
    //计算预约时间
    this.getReceiptWeek();
  },

  //打开备注
  showRemark() {

    this.setData({
      showRemark: true,
      openRemark: this.data.remark
    })
  },
  //关闭备注
  hideShowRemark() {
    this.setData({
      showRemark: false,
      openRemark: ''
    })
  },
  //确认备注
  sureRemark() {
    this.setData({
      showRemark: false,
      remark: this.data.openRemark,
    })
  },
  // 禁止input框输入表情
  regStrFn(str) {
    // 转换一下编码
    let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g,
      indexArr = reg.exec(str);
    if (str.match(reg)) {
      str = str.replace(reg, '');
    }
    let obj = {
      val: str,
      index: indexArr
    }
    return obj
  },

  //备注改变是
  remarkInput(e) {
    //特殊表情符号，空格
    let value = e.detail.value.replace(new RegExp("[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]", "gm"), "")
    let ageValue = value.replace(/\s+/g, '')
    this.setData({
      openRemark: ageValue,
    })
  },

  //大于3个商品时展开
  onGoodsOpen() {
    this.setData({
      isGoodsOpen: !this.data.isGoodsOpen,
    });
  },

  //打开店铺弹窗
  openShowShopList() {
    this.setData({
      showShopList: true,
    });
  },

  //关闭店铺弹窗
  hideShowShopList() {
    this.setData({
      showShopList: false,
    });
  },


  //打开优惠券弹窗
  openShowCouponList() {
    if (this.data.couponList.length == 0) {
      return;
    }
    this.setData({
      showCouponList: true,
    });
  },

  //关闭优惠券弹窗
  hideShowCouponList() {
    this.setData({
      showCouponList: false,
    });
  },
  hideShowVipCoupon() {
    this.setData({
      showVipCoupon: false,
    });
  },
  showVipCouponPrice() {
    this.setData({
      showVipCoupon: true
    })
  },

  //打开权益卡弹窗
  openShowEquityCardList() {
    if (this.data.equityCardList.length == 0) {
      return;
    }
    this.setData({
      showEquityCardList: true,
    });
  },

  //关闭权益卡弹窗
  hideEquityCardList() {
    this.setData({
      showEquityCardList: false,
    });
  },

  //确认权益卡
  sureEquityCardId() {
    this.setData({
      showEquityCardList: false,
    });
  },

  //打开选择预约时间
  openShowReceiptTime() {
    this.setData({
      showReceiptTime: true,
    });
  },

  //关闭选择预约时间
  hideShowReceiptTime() {
    this.setData({
      showReceiptTime: false,
    });
  },

  //打开外卖地址
  openShowAddressList() {
    if (this.data.orderAddress == '') {
      wx.navigateTo({
        url: '../address/addressList/addressList',
      })
    } else {
      this.setData({
        showAddressList: true,
        orderAddress2: this.data.orderAddress,
      });
    }

  },

  //关闭外卖地址
  hideShowAddressList() {
    this.setData({
      showAddressList: false,
    });
  },



  //支付方式改变
  onPayTypeChange(e) {
    this.setData({
      payType: e.currentTarget.dataset.type,
    });
    //储值支付时,如果余额不足不能提交订单
    if (this.data.payType == 4) {
      if (this.data.userInfo.cardRemaining * 1 < this.data.payAmt) {
        this.setData({
          submitClose: true,
        })
      }
    } else {
      this.setData({
        submitClose: false,
      })
    }
    if (this.data.payDiscountType == 1) {
      this.getPreOrder(false, false);
    }
  },

  //阻止冒泡事件
  handmiddle(e) {},
  handVip(e) {
    console.log('e', e)
    if (e.detail.value.length) {
      console.log('jinlaile')
      this.setData({
        useVipCheck: true,

      })
    } else {
      this.setData({
        useVipCheck: false,

      })
    }
    console.log('useVip', this.data.useVip)
    console.log('useVipCheck', this.data.useVipCheck)
  },

  //获取个人信息
  getUserBaseInfo() {
    let that = this;
    wx.showLoading({
      title: "加载中...",
      icon: "none"
    });
    return new Promise(function (resolve, reject) {
      getRequest("/api/vip/getUserBaseInfo", {
        memberId: app.myInfo.memberId
      }).then((res) => {

        if (res.data.data != null) {
          wx.setStorageSync('userInfo', res.data.data);
          that.setData({
            userInfo: res.data.data,
          })
        }
        wx.hideLoading();
        resolve(res);
      }).catch((err) => {
        wx.hideLoading();
        reject(err);
      });
    });
  },
  //获取店铺地址
  getShopSelfLift() {

    getRequest("/api/shop/getShopSelfLift", {}).then((res) => {

      res.data.data.forEach((item, index) => {
        if (item.id == 0) {
          this.setData({
            shopInfo: item,
          });
        }
      });
      this.setData({
        shopList: res.data.data,
      });
    }).catch((err) => {

    });
  },

  //获取优惠券,可用优惠券
  getMemberCoupon() {
    let that = this;
    let param = {
      beid: app.beid,
      memberId: app.myInfo.memberId,
      goodsList: that.data.goodsList,
      orderType: that.data.orderType,
      totalAmt: that.data.totalAmt,
      numberPeople: wx.getStorageSync('peopleNumber') || 0
    };
    postRequest("/api/coupon/getPrePayCoupon", param).then((res) => {

      if (res.data.data != null) {
        //赋值为未选，并区分可选不可选
        let couponList1 = [];
        let couponList2 = [];
        res.data.data.forEach((item, index) => {
          item.checked = false;
          if (item.isCanUse) {
            couponList1.push(item);
          } else {
            couponList2.push(item);
          }
        });
        that.setData({
          couponList: couponList1.concat(couponList2),
          useCouponList: couponList1,
        });
      }
    }).catch((err) => {});
  },

  //获取权益卡,可用权益卡
  getPrePayEquityCardOrder() {
    let that = this;
    let param = {
      beid: app.beid,
      memberId: app.myInfo.memberId,
      goodsList: that.data.goodsList,
      orderType: that.data.orderType,
      totalAmt: that.data.totalAmt,
      // coverCharge:10,
      numberPeople: wx.getStorageSync('peopleNumber') || 0
    };
    postRequest("/api/activity/getPrePayEquityCardOrder", param).then((res) => {

      if (res.data.data != null) {
        //赋值为未选，并区分可选不可选
        let equityCard1 = [];
        let equityCard2 = [];
        res.data.data.forEach((item, index) => {
          //判断使用默认图片
          if (item.cardThumb == '') {
            if (item.cardType == 1) {
              item.cardThumb = that.data.myEqCord1;
            } else if (item.cardType == 2) {
              item.cardThumb = that.data.myEqCord2;
            } else if (item.cardType == 3) {
              item.cardThumb = that.data.myEqCord3;
            } else if (item.cardType == 4) {
              item.cardThumb = that.data.myEqCord4;
            } else if (item.cardType == 5) {
              item.cardThumb = that.data.myEqCord5;
            }
          }
          item.checked = false;
          if (item.status == 1) {
            equityCard1.push(item);
          } else {
            equityCard2.push(item);
          }
        });
        that.setData({
          equityCardList: equityCard1.concat(equityCard2),
          useEquityCardList: equityCard1,
        });
      }
    }).catch((err) => {});
  },


  //获取地址列表
  getMemberAddressList() {
    let that = this;
    return new Promise(function (resolve, reject) {
      postRequest("/api/vip/member/getMemberAddressList", {
        beid: app.beid,
        memberId: app.myInfo.memberId,
        pageNo: 1,
        pageSize: 1000,
      }).then((res) => {

        if (res.data.data != null) {
          //默认优选，没有就选第一个
          let address = "";
          res.data.data.data.forEach((item, index) => {
            if (item.isDefault == 1) {
              address = item;
            }
          });
          if (address == "" && res.data.data.data.length != 0) {
            address = res.data.data.data[0];
          }
          that.setData({
            addressList: res.data.data.data,
            orderAddress: address,
            orderAddress2: address,
          });
        }
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    })

  },

  //获取外卖设置信息
  getDeliveryInfo() {
    let that = this;
    return new Promise(function (resolve, reject) {
      postParamsRequest("/api/delivery/get", {
        beid: app.beid,
      }).then((res) => {

        if (res.data.data != null) {
          that.setData({
            deliveryInfo: res.data.data
          })
        }
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    })
  },

  //获取会员配置
  getMemberConfig() {
    let that = this;
    return new Promise(function (resolve, reject) {
      getRequest("/api/vip/member/config", {}).then((res) => {

        if (res.data.data != null) {
          let rule = res.data.data.rechargeDiscountRule == '' ? [] : JSON.parse(res.data.data.rechargeDiscountRule);
          that.setData({
            rechargeDiscountRule: rule,
            payDiscountType: res.data.data.payDiscountType
          });
        }
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    })
  },

  //选择店铺时
  clickShopItem(e) {
    this.setData({
      shopInfo: e.currentTarget.dataset.shop,
    });
  },

  //选择优惠券时
  onCouponCheck(e) {

    for (let i = 0; i < this.data.couponList.length; i++) {
      if (e.detail.value.indexOf(this.data.couponList[i].memberCouponId.toString()) != -1) {
        //判断是否可共用
        if (this.data.memberCouponId.length != 0) {
          if (this.data.memberCouponId[0].isMutex == 0) {
            if (this.data.couponList[i].isMutex == 1) {
              wx.showToast({
                title: '该券不可共用',
                icon: "none",
              })
              this.data.couponList[i].checked = false;
              this.upDateCoupon(this.data.couponList);
              return;
            }
          } else {
            wx.showToast({
              title: '该券不可共用',
              icon: "none",
            })

            this.upDateCoupon(this.data.couponList);
            return;
          }
        }

        this.data.couponList[i].checked = true;
      } else {
        this.data.couponList[i].checked = false;
      }
    }
    //选中的优惠券
    this.upDateCoupon(this.data.couponList);
  },
  //选择权益卡时
  onEquityCardCheck(e) {

    for (let i = 0; i < this.data.equityCardList.length; i++) {
      if (e.detail.value.indexOf(this.data.equityCardList[i].memberEquityCardId.toString()) != -1) {
        this.data.equityCardList[i].checked = true;
      } else {
        this.data.equityCardList[i].checked = false;
      }
    }

    console.log('this.data.equityCardList', this.data.equityCardList)
    //选中的权益卡
    this.upDateEquityCard(this.data.equityCardList);
  },
  //点击可用优惠券时
  onCouponSelect(e) {
    let cIndex = e.currentTarget.dataset.index;

    if (this.data.couponList[cIndex].isCanUse == 0) {
      return;
    }
    //判断是否可共用
    // if (!this.data.couponList[cIndex].checked) {
    //   if (this.data.memberCouponId.length != 0) {
    //     if (this.data.memberCouponId[0].isMutex == 0) {
    //       if (this.data.couponList[cIndex].isMutex == 1) {
    //         wx.showToast({
    //           title: '该券不可共用',
    //           icon: "none",
    //         })
    //         this.data.couponList[cIndex].checked = false;
    //         this.upDateCoupon(this.data.couponList);
    //         return;
    //       }
    //     } else {
    //       wx.showToast({
    //         title: '该券不可共用',
    //         icon: "none",
    //       })
    //       this.upDateCoupon(this.data.couponList);
    //       return;
    //     }
    //   }
    // }

    for (let i = 0; i < this.data.couponList.length; i++) {
      if (i == cIndex) {
        this.data.couponList[cIndex].checked = !this.data.couponList[cIndex].checked;
      } else {
        this.data.couponList[i].checked = false;
      }
    }

    this.upDateCoupon(this.data.couponList);
  },
  //点击可用权益卡时
  onEquityCardSelect(e) {
    let cIndex = e.currentTarget.dataset.index;

    if (this.data.equityCardList[cIndex].status == 0) {
      return;
    }
    for (let i = 0; i < this.data.equityCardList.length; i++) {
      if (i == cIndex) {
        this.data.equityCardList[i].checked = !this.data.equityCardList[i].checked;
      } else {
        this.data.equityCardList[i].checked = false;
      }
    }
    this.upDateEquityCard(this.data.equityCardList);
  },
  //选中的优惠券
  upDateCoupon(couponList) {
    if (this.data.memberEquityCardId != "") {
      wx.showToast({
        title: '优惠券和权益卡不能同时使用',
        icon: 'none'
      });
      return false;
    }
    let memberCouponId = [];
    couponList.forEach((item, index) => {
      if (item.checked) {
        memberCouponId.push(item);
      }
    });

    this.setData({
      couponList: couponList,
      memberCouponId: memberCouponId,

    })
    if (this.data.memberCouponId.length) {
      this.setData({
        useMemberVipDiscount: 0
      })
    } else {
      this.setData({
        useMemberVipDiscount: 1
      })
    }
    console.log('memberCouponId', this.data.memberCouponId.length)
    console.log('useMemberVipDiscount', this.data.useMemberVipDiscount)
  },
  //选中的权益卡
  upDateEquityCard(equityCardList) {
    
    if (this.data.memberCouponId != "") {
      wx.showToast({
        title: '权益卡和优惠券不能同时使用',
        icon: 'none'
      });
      return false;
    }
    let memberEquityCardId = '';
    let memberEquityCardIdList = [];
    equityCardList.forEach((item, index) => {
      if (item.checked) {
        memberEquityCardId = item.memberEquityCardId;
        memberEquityCardIdList.push(item.memberEquityCardId)
      }
    });
    this.setData({
      equityCardList: equityCardList,
      memberEquityCardId: memberEquityCardId,
      useMemberVipDiscount: 0
    })
    if (memberEquityCardIdList.length) {
      this.setData({
        useMemberVipDiscount: 0
      })
    } else {
      this.setData({
        useMemberVipDiscount: 1
      })
    }
    console.log('memberEquityCardIdList', memberEquityCardIdList)

  },

  //确认优惠券
  sureCouponId() {
    this.setData({
      showCouponList: false,

    });
    //重新计算订单
    this.getPreOrder(false, true);
  },
  sureShowVipBtn() {
    console.log('user', this.data.useVip)
    // console.log('user',this.data.useVipCheck)
    if (this.data.useVipCheck) {
      this.setData({
        showVipCoupon: false,
        useMemberVipDiscount: 1,
        memberCouponId: [],
        memberEquityCardId: []
      })
    }else{
      this.setData({
        showVipCoupon: false,
        useMemberVipDiscount: 0,
  
      })
    }

    //重新计算订单
    this.getPreOrder(false, true);
  },

  //确认权益卡
  sureEquityCardId() {
    this.setData({
      showEquityCardList: false,
    });
    //重新计算订单
    this.getPreOrder(false, true);
  },



  //---------------------------------------------------------------------------------计算预约时间 开始

  // 计算方法，获取时间时段的小时
  computeHour(time1, time2, interval) {
    // 输入两个时间time1和time2还有时间间隔interval(分钟)，返回time1和time2之间每隔interval的时间
    // 时间格式为：HH:mm:ss
    // 如：time1=09:00，time2=18:00，interval=30，则返回的时间为：09:00，09:30，10:00，10:30，……，18:00
    function getTimeList(time1, time2, interval) { // time1, time2, interval
      var timeList = [];
      time1 = time1.split(':');
      time2 = time2.split(':');
      time1 = new Date(0, 0, 0, time1[0], time1[1], 0);
      time2 = new Date(0, 0, 0, time2[0], time2[1], 0);
      interval = interval * 60 * 1000;
      while (time1 < time2) {
        timeList.push(time1.format('hh:mm'));
        time1 = new Date(time1.getTime() + interval);
      }
      // timeList.push(time2.format('hh:mm'));   

      return timeList;
    }
    Date.prototype.format = function (format) {
      var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
      }
      if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in date)
        if (new RegExp("(" + k + ")").test(format))
          format = format.replace(RegExp.$1,
            RegExp.$1.length == 1 ? date[k] :
            ("00" + date[k]).substr(("" + date[k]).length));
      return format;
    }

    return getTimeList(time1, time2, interval)
  },
  //与当前小时比大小,大于当前时间返回true
  compareHour(end_time) {
    var date = new Date();
    var now_time = date.getMinutes() < 9 ? '0' + date.getMinutes() : date.getMinutes();
    var start_time = date.getHours() + ":" + now_time; //获取当前时分
    var s = start_time.split(":");
    var e = end_time.split(":");
    if (date.setHours(s[0], s[1]) > date.setHours(e[0], e[1])) {
      return false;
    } else {
      return true;
    }
  },
  //通过周几获取日期
  getDateByWeek(week) {
    const now = new Date();
    const nowTime = now.getTime();
    const day = now.getDay() > 0 ? now.getDay() : 7; // 表示当前是周几
    const oneDayTime = 24 * 60 * 60 * 1000; // 一天的总ms
    let dayNum = 1;
    if (week == "周一") {
      dayNum = 1;
    } else if (week == "周二") {
      dayNum = 2;
    } else if (week == "周三") {
      dayNum = 3;
    } else if (week == "周四") {
      dayNum = 4;
    } else if (week == "周五") {
      dayNum = 5;
    } else if (week == "周六") {
      dayNum = 6;
    } else if (week == "周日") {
      dayNum = 7;
    }
    if (dayNum == 7) {
      const SundayTime = nowTime + (7 - day) * oneDayTime
      const sunday = new Date(SundayTime)
      return sunday.format('yyyy-MM-dd');
    } else {
      const MondayTime = nowTime - (day - dayNum) * oneDayTime;
      const monday = new Date(MondayTime);
      return monday.format('yyyy-MM-dd');
    }
  },
  //通过周几获取数值
  getNumByWeek(week) {
    let dayNum = 1;
    if (week == "周一") {
      dayNum = 1;
    } else if (week == "周二") {
      dayNum = 2;
    } else if (week == "周三") {
      dayNum = 3;
    } else if (week == "周四") {
      dayNum = 4;
    } else if (week == "周五") {
      dayNum = 5;
    } else if (week == "周六") {
      dayNum = 6;
    } else if (week == "周日") {
      dayNum = 7;
    }
    return dayNum;
  },
  //获取周
  getReceiptWeek() {
    let weekD1 = this.data.shopInfo2.openDay;
    let weekD2 = sortToBig(weekD1.split(","));
    let weekD3 = []
    let weekNum = this.getNumByWeek(this.data.todayString);

    weekD2.forEach((item, index) => {
      if (item >= weekNum) {
        weekD3.push(item);
      }
    })

    //只获取今天，以及以后的
    let weekDays = [];
    let weekDaysW = [];
    //是否开启预约时间
    let isOpenCheckReceipt = false;
    //配送周期,默认一天
    let receiptPeriodTime = 1;
    //获取外卖配送信息
    if (this.data.deliveryInfo != null) {
      isOpenCheckReceipt = this.data.deliveryInfo.isOpenCheckReceipt == 1;
      receiptPeriodTime = this.data.deliveryInfo.receiptPeriodTime;
    }

    if (isOpenCheckReceipt) {
      weekD3.forEach((item, index) => {
        if (index < receiptPeriodTime) {
          weekDays.push(item);
        }
      });
    } else {
      weekD3.forEach((item, index) => {
        if (index == 0) {
          weekDays.push(item);
        }
      });
    }

    weekDaysW = getWeekByNum(weekDays);

    this.setData({
      checkReceiptWeekList: weekDaysW,
    });
    this.getReceiptTime();
  },
  //获取时间
  getReceiptTime() {
    let openTimePeriods = this.data.shopInfo2.openTimePeriods;
    //是否开启预约时间
    let isOpenCheckReceipt = false;
    console.log('营业时间', openTimePeriods);
    console.log('外卖配置', this.data.deliveryInfo);
    //配送时段范围，默认隔20
    let checkReceiptPeriod = 20;
    //如果有外卖配置则获取外卖配置的时段间隔
    if (this.data.deliveryInfo != null) {
      checkReceiptPeriod = this.data.deliveryInfo.checkReceiptPeriod;
      isOpenCheckReceipt = this.data.deliveryInfo.isOpenCheckReceipt == 1;
    }
    //营业时间按间隔分割
    let timeArr = [];

    //判断是否跨天
    let openTime2 = []
    for (let i = 0; i < openTimePeriods.length; i++) {
      if (moment(moment().format('YYYY-MM-DD') + ' ' + openTimePeriods[i].end).diff(moment(moment().format('YYYY-MM-DD') + ' ' + openTimePeriods[i].begin), 'minutes') < 0) {
        openTime2.push({
          end: openTimePeriods[i].end,
          begin: '00:00'
        });
        openTime2.push({
          end: '24:00',
          begin: openTimePeriods[i].begin
        });
      } else {
        openTime2.push(openTimePeriods[i])
      }
    }
    openTime2.forEach((item, index) => {
      let arr2 = this.computeHour(item.begin, item.end, checkReceiptPeriod);
      timeArr = timeArr.concat(arr2);
    });
    //如果时当天，排除已经过去的时间
    if (this.data.checkReceiptWeekList[this.data.checkReceiptWeekIndex] == this.data.todayString) {
      let timeArr1 = [];
      if (isOpenCheckReceipt) {
        timeArr.forEach((item, index) => {
          if (this.compareHour(item)) {
            timeArr1.push(item);
          }
        });
      }
      timeArr = timeArr1;
      if (app.shopInfo.shopOpen == 1 && this.data.isPlaceOrder == 1) {

      } else {
        if (this.data.orderType == 4) {
          timeArr.unshift("现在取餐");
        } else if (this.data.orderType == 1) {
          timeArr.unshift("现在送餐");
        }
      }

    }
    this.setData({
      checkReceiptTimeList: timeArr
    });

  },
  //---------------------------------------------------------------------------------计算预约时间 结束
  //确认预约时间
  sureReceiptTime() {
    this.setData({
      showReceiptTime: false,
    });
  },

  //选择预约时间
  clickReceiptTime(e) {
    console.log(e);
    let cIndex = e.currentTarget.dataset.index;
    this.setData({
      checkReceiptTimeIndex: cIndex,
    });
  },
  //选择预约时间周时
  clickReceiptWeek(e) {
    let cIndex = e.currentTarget.dataset.index;
    this.setData({
      checkReceiptWeekIndex: cIndex,
      checkReceiptTimeIndex: 0,
    });
    this.getReceiptTime();
  },

  //新增收货地址
  addAddressList() {
    wx.navigateTo({
      url: '../address/addAddress/addAddress',
    })
  },

  //确认收货地址
  sureAddressList() {
    this.setData({
      showAddressList: false,
      orderAddress: this.data.orderAddress2,
    });
    this.getPreOrder(false, true);
  },

  //收货地址点击时
  onAddressChange(e) {
    let cIndex = e.currentTarget.dataset.index
    this.setData({
      orderAddress2: this.data.addressList[cIndex],
    });
  },

  //前往充值页面
  toStoredValuePage() {
    wx.navigateTo({
      url: '../storedValue/storedValue',
    })
  },

  //计算直线距离
  getDistance2(lat1, lng1, lat2, lng2) {
    // 地球平均半径
    const EARTH_RADIUS = 6378137;
    // 把经纬度转为度（°）
    // 纬度
    let degree_lat1 = (lat1 * Math.PI) / 180.0;
    let degree_lat2 = (lat2 * Math.PI) / 180.0;
    let a = degree_lat1 - degree_lat2;
    // 经度
    let degree_lng1 = (lng1 * Math.PI) / 180.0;
    let degree_lng2 = (lng2 * Math.PI) / 180.0;
    let b = degree_lng1 - degree_lng2;
    // 距离 （单位：米）
    let s =
      2 *
      Math.asin(
        Math.sqrt(
          Math.pow(Math.sin(a / 2), 2) +
          Math.cos(degree_lat1) *
          Math.cos(degree_lat2) *
          Math.pow(Math.sin(b / 2), 2)
        )
      );
    s = s * EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000 / 1000;
    s = s.toFixed(2) * 1
    return s;
  },

  //手机号
  selfTakeMobileChange(e) {
    this.setData({
      selfTakeMobile: trim2(e.detail.value)
    })
  },

  //手机号码自动填写
  getPhoneNumber(e) {
    console.log(e);
    if (e.detail.errMsg != 'getPhoneNumber:ok') {
      return
    }
    let param = {
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData,
      memberId: app.myInfo.memberId,
    };
    postParamsRequest("/api/vip/getPhoneNumber", param).then((res) => {

      let data = res.data.data
      if (data.phoneNumber) {
        this.setData({
          selfTakeMobile: data.phoneNumber
        })
      }
    }).catch((err) => {});
  },

  //跳转技术支持页面
  goApp() {
    wx.navigateToMiniProgram({
      appId: 'wx4ef45ca79b4ddfac',
      path: 'pages/index1/index1',
      extraData: {
        foo: 'bar'
      },
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  },

  //确认订单，isRefreshCoupon:是否获取优惠券，isPayType是否初始化支付方式
  getPreOrder(isRefreshCoupon, isPayType) {
    this.setData({
      submitClose: true
    })
    //重新获取优惠券时把选择清空
    if (isRefreshCoupon) {
      this.setData({
        memberCouponId: [],
      });
    }
    let memberCouponId = [];
    let distance_new2 = 0;
    this.data.memberCouponId.forEach((item, index) => {
      memberCouponId.push(item.memberCouponId);
    });

    let param = {
      beid: app.beid,
      deliveryOrderId: this.data.deliveryOrderId, //配送订单ID(结算商品接口返回)
      goodsList: this.data.goodsList,
      memberCouponId: memberCouponId.join(","),
      useMemberVipDiscount: this.data.useMemberVipDiscount,
      cardId: this.data.memberEquityCardId,
      memberId: app.myInfo.memberId,
      numberPeople: wx.getStorageSync('peopleNumber') || 0,
      orderType: this.data.orderType,
      km: '',
      memberAddressId: '',
      payType: this.data.payType,
      // coverCharge:10

    };
    //外卖时传公里数和地址id
    if (this.data.orderType == 1) {
      if (this.data.deliveryInfo == null) {
        wx.showToast({
          title: '商家后台未设置外卖设置',
          icon: 'none'
        })
        return;
      }
      if (this.data.orderAddress == '') {
        wx.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return;
      }
      if (this.data.shopInfo.lnglat == undefined || this.data.shopInfo.lnglat == '') {
        wx.showToast({
          title: '商家门店设置未设置位置',
          icon: 'none'
        })
        return;
      }

      distance_new2 = this.getDistance2(Number(this.data.orderAddress.lnglat.split(',')[0]), Number(this.data.orderAddress.lnglat.split(',')[1]), Number(this.data.shopInfo.lnglat.split(',')[0]), Number(this.data.shopInfo.lnglat.split(',')[1]));

      if (distance_new2 > this.data.deliveryInfo.radiusRange * 1) {
        wx.showModal({
          title: '提示',
          content: '收货地址超过配送范围',
          showCancel: false
        })
        return;
      }

      param.km = distance_new2
      param.memberAddressId = this.data.orderAddress.id;
    }

    wx.showLoading({
      title: "加载中...",
      icon: "none"
    });
    postRequest("/api/order/getPreOrder", param).then((res) => {
      let data = res.data.data;
      //如果有余额，默认使用会员余额支付
      if (isPayType) {
        if (this.data.userInfo.cardRemaining * 1 >= data.payAmt * 1) {
          this.setData({
            payType: 4,
          });
          if (this.data.payDiscountType == 1) {
            this.getPreOrder(false, false);
          }
        } else {
          this.setData({
            payType: 1,
          });
        }
      }

      if (data.payAmt == 0) {
        this.setData({
          payType: 8,
        });
      }

      this.setData({
        boxAmt: data.boxAmt, //餐盒费
        coverChargeAmt: data.coverChargeAmt, //茶位费
        deliveryAmt: data.deliveryAmt, //配送费
        discountAmt: data.discountAmt, //优惠金额
        equityCardDiscountAmt: data.equityCardDiscountAmt, //权益卡优惠金额
        payAmt: data.payAmt, //实付金额
        serviceChargeAmt: data.serviceChargeAmt, //服务费
        totalAmt: data.totalAmt, //商品合计
        vipDiscountAmt: data.vipDiscountAmt, //会员折扣
        deliveryOrderId: data.deliveryOrderId, //配送订单ID(结算商品接口返回)
        shopAndMykm: distance_new2, //店铺和我的直线距离
        submitClose: false
      });

      //储值支付时,如果余额不足不能提交订单
      if (this.data.payType == 4) {
        if (this.data.userInfo.cardRemaining * 1 < this.data.payAmt) {
          this.setData({
            submitClose: true,
          })
        }
      }
      //获取可用优惠券
      if (isRefreshCoupon) {
        this.getMemberCoupon();
        this.getPrePayEquityCardOrder();
      }
      wx.hideLoading();
    }).catch((err) => {
      this.setData({
        submitClose: false
      })
      wx.hideLoading();
    });
  },
  //创建订单
  createFoodOrder() {

    let self = this;
    //订阅信息
    let tmplIds = this.data.tmplIds;
    //  && wx.getStorageSync('addBtnFoods')
    if (wx.getStorageSync('orderId') && wx.getStorageSync('paymentPriority') == 1 && (this.data.orderType == 2 || this.data.orderType == 3)) {
      wx.showModal({
        title: '提示',
        content: '该桌子已存在订单，是否加菜？',
        cancelText: "查看订单",
        success(res) {
          // wx.setStorageSync('addBtnFoods', false)
          if (res.confirm) {
            self.createFoodOrder2();
          } else {
            wx.navigateTo({
              url: '../orderDetail/orderDetail?orderId=' + app.globalData.orderId + "&orderType=" + this.data.orderType
            })
          }


        }
      })
    } else {

      if (tmplIds.length > 0 && wx.getStorageSync('paymentPriority') == 0) {
        //没有订阅权限唤起窗口
        // if (wx.requestSubscribeMessage) {
        wx.requestSubscribeMessage({
          tmplIds: tmplIds,
          success(_res) {},
          complete(_res) {
            self.createFoodOrder2();
          }
        })
        // }
      } else {
        self.createFoodOrder2();
      }
    }


  },
  getQueryDesk() {


    if (wx.getStorageSync('paymentPriority') == 1) {
      let parame = {
        deskId: wx.getStorageSync('deskId')
      }
      getRequest("/api/desk/queryDesk", parame).then((res) => {
        console.log('getQueryDesk', res.data.data)
        let obj = res.data.data;
        if (obj.orderId) {

          app.globalData.orderId = obj.orderId;
          app.globalData.deskId = obj.id;
          wx.setStorageSync('deskId', obj.id)
          wx.setStorageSync('deskName', obj.tableName)
          wx.setStorageSync('orderId', obj.orderId)
          this.setData({
            orderId: obj.orderId,
            deskName: obj.tableName,
            // showChooseScan:true
          })
        } else {
          // wx.clearStorageSync("deskName")
          // wx.clearStorageSync('deskCode')
          // wx.clearStorageSync('deskId')
          wx.clearStorageSync('orderId')
        }


      }).catch((err) => {

      });
    }
  },
  //创建订单
  createFoodOrder2() {
    let self = this;
    if (this.data.submitLock) {
      return
    }
    if (self.data.orderType == 1 && self.data.deliveryInfo != null && self.data.deliveryInfo.startPrice * 1 > self.data.totalMoney) {
      wx.showModal({
        title: '提示',
        content: '起送价为' + self.data.deliveryInfo.startPrice + '元，您的订单低于起送价',
        showCancel: false
      })
      return
    }

    let memberCouponId = [];
    this.data.memberCouponId.forEach((item, index) => {
      memberCouponId.push(item.memberCouponId);
    });

    let parame = {
      address: "",
      addressLabel: "",
      deskName: "",
      deskId: "",
      beid: app.beid,
      cardId: this.data.memberEquityCardId,
      checkReceiptTime: "",
      deliveryOrderId: "",
      goodsList: this.data.goodsList,
      km: '',
      memberAddressId: '',
      memberCouponId: memberCouponId.join(","),
      memberId: app.myInfo.memberId,
      mobile: "",
      numberPeople: wx.getStorageSync('peopleNumber') || 0,
      orderType: this.data.orderType,
      payAmt: this.data.payAmt,
      payType: this.data.payType,
      realName: '',
      remark: this.data.remark,
      useMemberVipDiscount: this.data.useMemberVipDiscount,
    }

    //1-外卖，2-堂食，3-服务员点餐,4-自取
    if (this.data.orderType == 1) {
      if (this.data.orderAddress == "") {
        wx.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return;
      } else {
        parame.address = this.data.orderAddress.address;
        parame.addressLabel = this.data.orderAddress.addressName;
        parame.mobile = this.data.orderAddress.mobile;
        parame.deliveryOrderId = this.data.deliveryOrderId;
        parame.km = this.data.shopAndMykm;
        parame.memberAddressId = this.data.orderAddress.id;
      }

      //取餐时间
      let checkReceiptTime = "";
      if (this.data.checkReceiptTimeList[this.data.checkReceiptTimeIndex] == "现在送餐") {
        // var date = new Date();
        // var now_minute = date.getMinutes() < 9 ? '0' + date.getMinutes() : date.getMinutes();
        // var now_hour1 = date.getHours() < 9 ? '0' + date.getHours() : date.getHours();
        // var now_hour = now_hour1 + ":" + now_minute + ":00";

        // let selectDate = this.getDateByWeek(this.data.checkReceiptWeekList[this.data.checkReceiptWeekIndex]);
        // checkReceiptTime = selectDate + " " + now_hour;
      } else {
        var now_hour = this.data.checkReceiptTimeList[this.data.checkReceiptTimeIndex] + ":00";
        let selectDate = this.getDateByWeek(this.data.checkReceiptWeekList[this.data.checkReceiptWeekIndex]);
        checkReceiptTime = selectDate + " " + now_hour;
      }

      parame.realName = this.data.orderAddress.realName;
      parame.checkReceiptTime = checkReceiptTime;

    }
    //堂食
    if ((this.data.orderType == 2 && wx.getStorageSync('paymentPriority') == 1) || (wx.getStorageSync('paymentPriority') == 1 && this.data.orderType == 3)) {
      if (wx.getStorageSync('deskId') == "") {
        wx.showToast({
          title: '请扫描桌号',
          icon: 'none'
        })
        return;
      }
      parame.deskName = this.data.deskName || wx.getStorageSync('deskName');
      parame.deskId = this.data.deskId || wx.getStorageSync('deskId');
      app.globalData.deskId = this.data.deskId || wx.getStorageSync('deskId');
      parame.tableId = this.data.deskId || wx.getStorageSync('deskId');
      parame.teaName = "无茶位费";
      parame.orderId = app.globalData.orderId || wx.getStorageSync('orderId');
      parame.numberPeople = wx.getStorageSync('peopleNumber') || 0

    }
    //自取
    if (this.data.orderType == 4) {
      if (this.data.shopInfo.name == undefined || this.data.shopInfo.name == '') {
        wx.showToast({
          title: '请选择门店',
        })
        return;
      } else {
        parame.address = this.data.shopInfo.address;
        parame.addressLabel = this.data.shopInfo.name;
      }
      //自取时间
      let checkReceiptTime = "";
      if (this.data.checkReceiptTimeList[this.data.checkReceiptTimeIndex] == "现在取餐") {
        // var date = new Date();
        // var now_minute = date.getMinutes() < 9 ? '0' + date.getMinutes() : date.getMinutes();
        // var now_hour1 = date.getHours() < 9 ? '0' + date.getHours() : date.getHours();
        // var now_hour = now_hour1 + ":" + now_minute + ":00";

        // let selectDate = this.getDateByWeek(this.data.checkReceiptWeekList[this.data.checkReceiptWeekIndex]);
        // checkReceiptTime = selectDate + " " + now_hour;
      } else {
        var now_hour = this.data.checkReceiptTimeList[this.data.checkReceiptTimeIndex] + ":00";
        let selectDate = this.getDateByWeek(this.data.checkReceiptWeekList[this.data.checkReceiptWeekIndex]);
        checkReceiptTime = selectDate + " " + now_hour;
      }

      parame.checkReceiptTime = checkReceiptTime;
      parame.selfLiftId = this.data.shopInfo.id;
      if (this.data.isOpenRetention == 1) {
        this.setData({
          selfTakeMobile: trim2(this.data.selfTakeMobile)
        })
        if (this.data.selfTakeMobile == '' || this.data.selfTakeMobile.length != 11) {
          wx.showToast({
            title: '请正确输入手机号码',
            icon: 'none'
          })
          return
        }
        parame.mobile = this.data.selfTakeMobile;
      }
    }


    wx.showLoading({
      title: "提交中...",
      icon: "none",
      mask: true,
    });
    this.setData({
      submitLock: true
    })
    let sureOrderType = this.data.orderType
    console.log('付款里面的字段', app.globalData, app.globalData?.orderId, app.globalData?.paymentPriority, app.globalData?.orderType)
    if (wx.getStorageSync('orderId') && wx.getStorageSync('paymentPriority') == 1 && (this.data.orderType == 2 || this.data.orderType == 3)) {
      postRequest("/api/order/addFoodOrder", parame).then((res) => {
        //创建订单成功后，清除购物车中选中的商品
        self.clearCartList();
        self.setData({
          goodsList: [],
        })
        wx.redirectTo({
          url: '../orderDetail/orderDetail?orderId=' + wx.getStorageSync('orderId') + "&orderType=" + this.data.orderType
        })


      }).catch((err) => {
        wx.hideLoading();
        self.setData({
          submitLock: false
        })
      });
    } else if (wx.getStorageSync('paymentPriority') == 1 && !wx.getStorageSync('orderId') && (this.data.orderType == 2 || this.data.orderType == 3)) {
      // parame.orderType = 2;

      // return
      postRequest("/api/order/quickOrder", parame).then((res) => {
        console.log(res.data.data);
        //创建订单成功后，清除购物车中选中的商品
        self.clearCartList();
        self.setData({
          goodsList: [],
        })

        app.globalData.orderId = res.data.data.orderId;
        wx.setStorageSync('orderId', res.data.data.orderId)
        wx.redirectTo({
          url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + this.data.orderType
        })

      }).catch((err) => {
        wx.hideLoading();
        self.setData({
          submitLock: false
        })
      });

    } else {
      parame.deskName = this.data.deskName || wx.getStorageSync('deskName');
      parame.deskId = this.data.deskId || wx.getStorageSync('deskId');
      app.globalData.deskId = this.data.deskId || wx.getStorageSync('deskId');
      parame.tableId = this.data.deskId || wx.getStorageSync('deskId');
      postRequest("/api/order/createFoodOrder", parame).then((res) => {

        app.globalData.orderId = res.data.data.orderId
        //创建订单成功后，清除购物车中选中的商品
        self.clearCartList();
        self.setData({
          goodsList: [],
        })
        //判断是微信支付还是储值
        if (this.data.payType == 1) {
          postParamsRequest("/api/order/payFoodsOrder", {
            orderId: res.data.data.orderId,
          }).then((res2) => {

            let data = res2.data.data;
            wx.requestPayment({
              'timeStamp': data.timeStamp,
              'nonceStr': data.nonceStr,
              'package': data.package,
              'signType': data.signType,
              'paySign': data.paySign,
              'success': function (res3) {

                wx.hideLoading();
                self.setData({
                  isPay: true,
                })
                //支付成功跳转订单详情页
                wx.redirectTo({
                  url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + sureOrderType
                })
              },
              'fail': function (err) {

                wx.hideLoading();
                self.setData({
                  submitLock: false,
                })
                showToast("支付失败");
                //支付成功跳转订单详情页
                wx.redirectTo({
                  url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + sureOrderType
                })
              }
            })

          }).catch((err) => {
            wx.hideLoading();
            self.setData({
              submitLock: false
            })
          });
        } else if (this.data.payType == 4) {
          if (res.data.data.payStatus == false) {
            wx.showToast({
              title: '储值支付失败',
            })
          } else {
            wx.showToast({
              title: '储值支付成功',
            })
            wx.redirectTo({
              url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + sureOrderType
            })
          }
          wx.hideLoading();
          self.setData({
            submitLock: false
          })
        } else if (this.data.payType == 8) {
          if (res.data.data.payStatus == false) {
            wx.showToast({
              title: '支付失败',
            })
          } else {
            wx.showToast({
              title: '支付成功',
            })
            wx.redirectTo({
              url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + sureOrderType
            })
          }
          wx.hideLoading();
          self.setData({
            submitLock: false
          })
        }


      }).catch((err) => {
        wx.hideLoading();
        self.setData({
          submitLock: false
        })
      });
    }



  },
  payTypeBtn() {
    //判断是微信支付还是储值
    if (this.data.payType == 1) {
      postParamsRequest("/api/order/payFoodsOrder", {
        orderId: res.data.data.orderId,
      }).then((res2) => {

        let data = res2.data.data;
        wx.requestPayment({
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': data.signType,
          'paySign': data.paySign,
          'success': function (res3) {
            wx.hideLoading();
            self.setData({
              isPay: true,
            })
            //支付成功跳转订单详情页
            wx.redirectTo({
              url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + this.data.orderType
            })
          },
          'fail': function (err) {

            wx.hideLoading();
            self.setData({
              submitLock: false,
            })
            showToast("支付失败");
            //支付成功跳转订单详情页
            wx.redirectTo({
              url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + this.data.orderType
            })
          }
        })

      }).catch((err) => {
        wx.hideLoading();
        self.setData({
          submitLock: false
        })
      });
    } else if (this.data.payType == 4) {
      if (res.data.data.payStatus == false) {
        wx.showToast({
          title: '储值支付失败',
        })
      } else {
        wx.showToast({
          title: '储值支付成功',
        })
        wx.redirectTo({
          url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId
        })
      }
      wx.hideLoading();
      self.setData({
        submitLock: false
      })
    } else if (this.data.payType == 8) {
      if (res.data.data.payStatus == false) {
        wx.showToast({
          title: '支付失败',
        })
      } else {
        wx.showToast({
          title: '支付成功',
        })
        wx.redirectTo({
          url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId
        })
      }
      wx.hideLoading();
      self.setData({
        submitLock: false
      })
    }
  },
  //清除购物车中选中的商品
  clearCartList() {
    let cartList = app.globalData.cartList;
    let cartL = [];
    cartList.forEach((item, index) => {
      if (item.checked == false) {
        cartL.push(item);
      }
    });
    app.globalData.cartList = cartL;
  },

  //获取订阅信息
  getSubscriptionMessageTplIds() {
    let that = this;
    //支付成功，取消订单，取餐通知
    getRequest("/api/msg/getSubscriptionMessageTplIds", {
      msgType: '1,3,20'
    }).then((_res) => {

      if (_res.data.data.length > 0) {
        let setList = []
        wx.getSetting({
          withSubscriptions: true,
          success(setRes) {

            if (setRes.subscriptionsSetting) {
              setList = Object.keys(setRes.subscriptionsSetting)
            }
            let tmplIds = []
            _res.data.data.forEach(element => {
              if (setList.indexOf(element) == -1) {
                tmplIds.push(element)
              }
            });
            that.setData({
              tmplIds: tmplIds
            })
          },
          fail() {}
        })
      } else {}
    }).catch((err) => {

    });
  },

  //初始化信息
  async initData() {
    //技术支持图片
    var imgIcon = wx.getStorageSync('shopInfo');
    if (imgIcon != undefined && imgIcon != '') {

      this.setData({
        technicalSupportIcon: imgIcon.technicalSupportIcon,
        isOpenRetention: imgIcon.isOpenRetention,
        isPlaceOrder: imgIcon.isPlaceOrder, //是否可以预约下单
      })
    }

    //门店列表
    this.getShopSelfLift();
    //会员配置，充值的信息
    await this.getMemberConfig();
    //用户基本信息
    await this.getUserBaseInfo();
    //如果时外卖，则获取收货地址
    if (this.data.orderType == 1) {
      await this.getMemberAddressList();
    }
    //外卖自提获取外卖设置信息
    if (this.data.orderType == 1) {
      await this.getDeliveryInfo();
      if (this.data.deliveryInfo == null) {
        wx.showModal({
          title: '提示',
          content: "商家未设置外卖设置",
          showCancel: false
        })
        return;
      }
    } else {
      await this.getDeliveryInfo();
    }

    let cartList = app.globalData.cartList;
    console.log('catList', cartList)
    let cartList2 = [];
    //获取购物车选中的商品
    cartList.forEach((item, index) => {
      item.discount = 1;
      item.goodsPrice = item.shopPrice;
      item.remark = "";
      item.isPack = 0;
      item.isPresent = 0;
      item.isQuicken = 0;
      item.isWait = 0;

      if (item.checked) {
        cartList2.push(item);
      }
    });
    //计算件数
    let goodsCount = 0;
    let totalMoney = 0;
    cartList2.forEach((item, index) => {
      goodsCount += item.count;
      totalMoney += item.count * item.shopPrice
    });
    this.setData({
      goodsList: cartList2,
      goodsListCount: goodsCount,
      totalMoney: totalMoney,
      todayString: getWeekByDate(new Date()),
      shopInfo2: app.shopInfo,
    });
    //计算预约时间
    this.getReceiptWeek();
    //计算订单
    this.getPreOrder(true, true);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('this.data.orderTypeononLoad', this.data.orderType)
    console.log('app.globalData?.paymentPriority', app.globalData?.paymentPriority)
    console.log('app.globalData?.addBtn', app.globalData?.addBtn)
    console.log('app.globalData.orderType', app.globalData.orderType)
    console.log('app.globalData?.orderId', app.globalData?.orderId)
    console.log('app.globalData.orderType ', app.globalData.orderType)
    console.log('app.globalData.deskName', wx.getStorageSync('deskName'))
    console.log('app.globalData.deskId', wx.getStorageSync('deskId'))
    console.log('app.globalData.paymentPriority', wx.getStorageSync('paymentPriority'))
    console.log('options.orderType ', options.orderType)
    console.log('options', options)
    //获取参数，是堂食还是外卖
    console.log("获取参数，是堂食还是外卖", options.orderType, options)
    // app.globalData.orderId = options.orderId;
    // if(options.orderType != 5){
    //   app.globalData?.orderType = 1;
    //   this.setData({
    //     paymentPriorityOrder:1
    //   })
    // }

    if (options.orderType) {

      this.setData({
        orderMode: options.saleType,
        orderType: options.orderType,
        deskName: options.deskCode, //桌号
        // deskName: "室内1号桌",
        deskId: options.deskId, //桌号id
        // deskId: "3737", //桌号id
      });
      if (options.orderType == 4 || options.orderType == 1) {
        this.setData({
          paymentPriority: 0,
        })
        wx.setStorageSync('paymentPriority', 0)
      }
    }

    //获取授权信息
    this.getSubscriptionMessageTplIds();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    app.globalData.isTrue = false;
    if (this.data.isPay) {
      return;
    }
    //如果没有token,则需要重新登录获取个人信息等，避免缺少id导致数据无法获取
    if (app.token == "" || app.token == undefined) {
      app.initLogin().then(res => {
        this.initData();
      }).catch(err => {})
    } else {
      this.initData();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})